package authpublish

import (
	"net/http"

	"blogcenter/internal/logic/authpublish"
	"blogcenter/internal/svc"
	"blogcenter/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

const (
	defaultMultipartMemory = 32 << 20 // 32 MB
)

func PublishPhotoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 1. 解析 multipart 表单
		if err := r.ParseMultipartForm(defaultMultipartMemory); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		// 2. 获取上传的文件
		file, header, err := r.FormFile("file")
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		defer file.Close()

		// 3. 读取文件内容到内存
		fileBytes := make([]byte, header.Size)
		_, err = file.Read(fileBytes)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		// 4. 创建请求对象（保持与API定义一致）
		req := &types.PhotoUploadRequest{
			File: fileBytes, // 将文件内容赋值给File字段
		}

		// 5. 调用业务逻辑
		l := authpublish.NewPublishPhotoLogic(r.Context(), svcCtx)
		resp, err := l.PublishPhoto(req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
